package com.rules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gillion.grule.client.utils.Streams;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.rules.admin.dao.RulePackageDao;
import com.rules.admin.domain.DataType;
import com.rules.admin.domain.Page;
import com.rules.admin.entity.*;
import com.rules.admin.login.UserHolder;
import com.rules.admin.service.*;


import com.rules.admin.service.decision.DecisionCellService;
import com.rules.admin.service.decision.DecisionColumnConfigService;
import com.rules.admin.service.decision.DecisionRowService;
import com.rules.admin.service.decision.DecisionTableService;
import com.rules.admin.vo.*;

import com.rules.admin.utils.Constant;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry;

@Service
public class RulePackageServiceImpl extends ServiceImpl<RulePackageDao, RulePackage> implements RulePackageService {
   @Autowired
   private BusinessModelAttributeService businessModelAttributeService;
   @Autowired
   private RuleAssemblyService ruleAssemblyService;
   @Autowired
   private DecisionTableService decisionTableService;
   @Autowired
   private DecisionTreeService decisionTreeService;
   @Autowired
   private RuleService ruleService;
   @Autowired
   private ProjectService projectService;
   @Autowired
   private UserHolder<RuleUser> userHolder;
   @Autowired
   private UserGroupService userGroupService;
   @Autowired
   private RuleUserRoleService ruleUserRoleService;
   @Autowired
   private BusinessModelService businessModelService;
   @Autowired
   private UnitCaseService unitCaseService;
   @Autowired
   private PermissionService permissionService;
//   @Autowired
//   private PermissionReferenceMapper permissionReferenceMapper;
   @Autowired
   private SysGroupUserRoleService sysGroupUserRoleService;
   @Autowired
   private RuleVariableService ruleVariableService;
   @Autowired
   private DecisionColumnConfigService decisionColumnConfigService;
   @Autowired
   private DecisionRowService decisionRowService;
   @Autowired
   private DecisionCellService decisionCellService;
   @Autowired
   private TreeNodeService treeNodeService;
   @Autowired
   private TreeDedutionService treeDedutionService;

   public static final int STATUS_EDIT = 0;
   public static final int STATUS_PUBLISH = 1;
   public static final int STATUS_PUBLISHED = 2;


   @Override
   public List<RulePackage> getRulePackagesByProjectIds(List<Long> projectIds) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();

      if (projectIds.size() > 0) {
         queryWrapper.in(RulePackage::getProjectid, projectIds);
      } else {
         queryWrapper.eq(RulePackage::getId,-1L);

      }

      return this.list(queryWrapper);
   }

   @Override
   public List<RulePackage> getRulePackagesBypackageIds(List<Long> packageIds) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();

      if (packageIds.size() > 0) {
         queryWrapper.in(RulePackage::getId, packageIds);
      } else {
         queryWrapper.eq(RulePackage::getId,-1L);

      }
      return this.list(queryWrapper);
   }

   @Override
   public List<UserPermissionInfo> selectUserPermissionInfos(Long targetId, Integer targetType, Integer mode, String userName) {
      return this.baseMapper.selectUserPermissionInfos(targetId, targetType, mode, userName);
   }

   @Override
   public List<UserGroupPermissionInfo> selectUserGroupPermissionInfos(Long targetId, Integer targetType, Integer mode, String groupName) {
      return this.baseMapper.selectUserGroupPermissionInfos(targetId, targetType, mode, groupName);
   }


   public RulePackage insert(RulePackage rulePackage) {
      this.save(rulePackage);
      return rulePackage;
   }

   public RulePackage update(RulePackage rulePackage) {
       this.updateById(rulePackage);
       return rulePackage;
   }

   public void delete(long id) {
      this.removeById(id);
      this.ruleAssemblyService.deleteByRulePackage(id);
   }



   public void updateStatus(long id, Integer status) {
      RulePackage rulePackage = new RulePackage();
      rulePackage.setId(id);
      rulePackage.setStatus(status);
      this.updateById(rulePackage);
   }

   public Page queryPage(String name, String artifactId, String remark, Page page) {
      RulePackageParams packageParams = new RulePackageParams();
      packageParams.setPage(page);
      if (name != null && name != "") {
         packageParams.setPackageName("%" + name + "%");
      }

      if (artifactId != null && artifactId != "") {
         packageParams.setArtifactId(artifactId);
      }

      if (remark != null && remark != "") {
         packageParams.setRemark("%" + remark + "%");
      }

      Map<Long, ProjectRoleVO> projectRoleVOMap = this.projectService.getProjectRoleVOs(((RuleUser)this.userHolder.getUser()).getId());
      List<Long> packageIds = new ArrayList();
      Set set = projectRoleVOMap.entrySet();
      Iterator i = set.iterator();

      while(i.hasNext()) {
         Entry<Long, ProjectRoleVO> entry = (Entry)i.next();
         if (((ProjectRoleVO)entry.getValue()).getRoles().contains(0)) {
            packageIds.add(entry.getKey());
         }
      }

      packageParams.setProjectIds(packageIds);

      return this.baseMapper.findPackages(packageParams);
   }

   public RulePackage getRulePackage(String groupId, String artifactId, String version) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getGroupId,groupId).eq(RulePackage::getArtifactId,artifactId).eq(RulePackage::getVersion,version);
      return (RulePackage)this.baseMapper.selectOne(queryWrapper);

   }

   public RulePackage getRulePackageByArtifactId(String artifactId, String version) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getArtifactId,artifactId).eq(RulePackage::getVersion,version);
      return (RulePackage)this.baseMapper.selectOne(queryWrapper);
   }

   public RulePackage getActiveRulePackage(String groupId, String artifactId) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getGroupId,groupId).eq(RulePackage::getArtifactId,artifactId).eq(RulePackage::getStatus,1);
      return (RulePackage)this.baseMapper.selectOne(queryWrapper);
   }

   public List<RulePackage> getRulePackagesByBusinessModel(long businessModelId) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getBusinessModelId,businessModelId);
      return this.baseMapper.selectList(queryWrapper);
   }

   public void updateRulePackageByPublished(long id) {
      RulePackage rulePackage = (RulePackage)this.baseMapper.selectById(id);
      this.publish2Published(rulePackage);
      this.updateStatus(id, 1);
   }

   private void publish2Published(RulePackage rulePackage) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getGroupId,rulePackage.getGroupId()).eq(RulePackage::getArtifactId,rulePackage.getArtifactId()).eq(RulePackage::getStatus,1);
      RulePackage record = new RulePackage();
      record.setStatus(2);
      this.baseMapper.update(record,queryWrapper);
   }

   public RulePackage updateRulePackageByPublish(long id, String version) throws Exception {
      RulePackage rulePackage = (RulePackage)this.baseMapper.selectById(id);
      this.publish2Published(rulePackage);
      this.updateStatus(id, 1);
      rulePackage.setId((Long)null);
      rulePackage.setVersion(version);
      rulePackage.setStatus(0);
      rulePackage.setCreateTime(new Date());
      this.insert(rulePackage);
      this.copyRulePackage(rulePackage, id);
      return rulePackage;
   }

   public void copy(RulePackage rulePackage, Long id) {
      RulePackage newRulePackage = this.baseMapper.selectById(id);
      Project project = (Project)this.projectService.getById(rulePackage.getProjectid());
      newRulePackage.setId((Long)null);
      newRulePackage.setProjectid(project.getId());
      newRulePackage.setGroupId(project.getProjectCode());
      List<BusinessModelAttributeEntity> list = this.businessModelAttributeService.getModelAttributesByModelId(newRulePackage.getBusinessModelId());
      List<BusinessModelAttributeEntity> newList = new ArrayList();
      Iterator var7 = list.iterator();

      while(var7.hasNext()) {
         BusinessModelAttributeEntity businessModelAttributeEntity = (BusinessModelAttributeEntity)var7.next();
         if (businessModelAttributeEntity.getParentId() == null) {
            newList.add(businessModelAttributeEntity);
         }
      }

      this.copyBusModel(newList, id, (Long)null);
      newRulePackage.setBusinessModelId(id);
      newRulePackage.setName(rulePackage.getName());
      newRulePackage.setArtifactId(rulePackage.getArtifactId());
      newRulePackage.setVersion("1.0.0");
      newRulePackage.setStatus(0);
      newRulePackage.setCreateTime(new Date());
      this.insert(newRulePackage);
      this.copyRulePackage(newRulePackage, rulePackage.getId());
   }

   @Override
   public RulePackage getByGroupId(String groupId) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper();
      queryWrapper.eq(RulePackage::getArtifactId,groupId);
      return (RulePackage)this.baseMapper.selectOne(queryWrapper);
   }


   private void copyBusModel(List<BusinessModelAttributeEntity> list, Long id, Long parentId) {
      Iterator var4 = list.iterator();

      while(var4.hasNext()) {
         BusinessModelAttributeEntity businessModelAttributeEntity = (BusinessModelAttributeEntity)var4.next();
         if (parentId != null) {
            businessModelAttributeEntity.setParentId(parentId);
         }

         if (businessModelAttributeEntity.getDataType()== DataType.Object ) {
            Long newParentId = this.copyBusModelAtt(businessModelAttributeEntity, id);
            List<BusinessModelAttributeEntity> children = this.businessModelAttributeService.getModelAttributesByParentId(businessModelAttributeEntity.getId());
            this.copyBusModel(children, id, newParentId);
         } else {
            this.copyBusModelAtt(businessModelAttributeEntity, id);
         }
      }

   }

   public Long copyBusModelAtt(BusinessModelAttributeEntity businessModelAttributeEntity, Long id) {
      BusinessModelAttributeEntity bma = new BusinessModelAttributeEntity();
      bma.setValueExpress(businessModelAttributeEntity.getValueExpress());
      bma.setBusinessModelId(id);
      bma.setAttrName(businessModelAttributeEntity.getAttrName());
      bma.setValueType(businessModelAttributeEntity.getValueType());
      bma.setDataType(businessModelAttributeEntity.getDataType());
      bma.setParentId(businessModelAttributeEntity.getParentId());
      this.businessModelAttributeService.save(bma);
      return bma.getId();
   }

   public void copyRulePackage(RulePackage rulePackage, Long id) {
      List<RuleVariable> packageVariables = this.ruleVariableService.getByScopeAndScopeId(1, id);
      Iterator var4 = packageVariables.iterator();

      while(var4.hasNext()) {
         RuleVariable packageVariable = (RuleVariable)var4.next();
         packageVariable.setId((Long)null);
         packageVariable.setScopeId(rulePackage.getId());
         this.ruleVariableService.save(packageVariable);
      }

      List<RuleAssembly> ruleAssemblies = this.ruleAssemblyService.getRuleAssemblyByPackageId(id);
      Iterator var23 = ruleAssemblies.iterator();

      Long decisionTableId;
      List decisionRows;
      List treeDedutions;
      Iterator var14;
      while(var23.hasNext()) {
         RuleAssembly ruleAssembly = (RuleAssembly)var23.next();
         List<Rule> rules = this.ruleService.getRuleListByAssemblyId(ruleAssembly.getId());
         decisionTableId = ruleAssembly.getId();
         ruleAssembly.setId((Long)null);
         ruleAssembly.setPackageId(rulePackage.getId());
         this.ruleAssemblyService.insert(ruleAssembly);
         decisionRows = this.ruleVariableService.getByScopeAndScopeId(2, decisionTableId);
         Iterator var10 = decisionRows.iterator();

         while(var10.hasNext()) {
            RuleVariable assemblyVariable = (RuleVariable)var10.next();
            assemblyVariable.setId((Long)null);
            assemblyVariable.setScopeId(ruleAssembly.getId());
            this.ruleVariableService.save(assemblyVariable);
         }

         var10 = rules.iterator();

         while(var10.hasNext()) {
            Rule rule = (Rule)var10.next();
            Long ruleId = rule.getId();
            rule.setId((Long)null);
            rule.setRuleAssemblyId(ruleAssembly.getId());
            this.ruleService.insert(rule);
            treeDedutions = this.ruleVariableService.getByScopeAndScopeId(3, ruleId);
            var14 = treeDedutions.iterator();

            while(var14.hasNext()) {
               RuleVariable ruleVariable = (RuleVariable)var14.next();
               ruleVariable.setId((Long)null);
               ruleVariable.setScopeId(rule.getId());
               this.ruleVariableService.save(ruleVariable);
            }
         }
      }

      List<DecisionTable> decisionTables = this.decisionTableService.getDecisionTablesByPackageId(id);
      Iterator var25 = decisionTables.iterator();

      List decisionColumnConfigs;
      HashMap nodeMap;
      Iterator var37;
      Iterator var43;
      while(var25.hasNext()) {
         DecisionTable decisionTable = (DecisionTable)var25.next();
         decisionTableId = decisionTable.getId();
         decisionTable.setId((Long)null);
         decisionTable.setRulePackageId(rulePackage.getId());
         this.decisionTableService.save(decisionTable);
         decisionRows = this.decisionRowService.getRowsByTableId(decisionTableId);
         decisionColumnConfigs = this.decisionColumnConfigService.getColumnConfigsByTableId(decisionTableId);
         nodeMap = new HashMap();
         Map<Long, Long> colCellMap = new HashMap();
         var37 = decisionRows.iterator();

         DecisionColumnConfig decisionColumnConfig;
         while(var37.hasNext()) {
            DecisionRow decisionRow = (DecisionRow)var37.next();
            var43 = decisionColumnConfigs.iterator();

            while(var43.hasNext()) {
               decisionColumnConfig = (DecisionColumnConfig)var43.next();
               DecisionCell decisionCell = this.decisionCellService.getCellByRowIdAndColId(decisionRow.getId(), decisionColumnConfig.getId());
               if (decisionCell != null) {
                  colCellMap.put(decisionColumnConfig.getId(), decisionCell.getId());
               }
            }

            nodeMap.put(decisionRow.getId(), colCellMap);
         }

         Map<Long, Long> rowMap = new HashMap();
         Map<Long, Long> colMap = new HashMap();
         var43 = decisionRows.iterator();

         Long colId;
         while(var43.hasNext()) {
            DecisionRow decisionRow = (DecisionRow)var43.next();
            colId = decisionRow.getId();
            decisionRow.setId((Long)null);
            decisionRow.setTableId(decisionTable.getId());
            this.decisionRowService.save(decisionRow);
            rowMap.put(colId, decisionRow.getId());
         }

         var43 = decisionColumnConfigs.iterator();

         while(var43.hasNext()) {
            decisionColumnConfig = (DecisionColumnConfig)var43.next();
            colId = decisionColumnConfig.getId();
            decisionColumnConfig.setId((Long)null);
            decisionColumnConfig.setTableId(decisionTable.getId());
            this.decisionColumnConfigService.save(decisionColumnConfig);
            colMap.put(colId, decisionColumnConfig.getId());
         }

         List<DecisionRow> decisionRows1 = this.decisionRowService.getRowsByTableId(decisionTableId);
         List<DecisionColumnConfig> decisionColumnConfigs1 = this.decisionColumnConfigService.getColumnConfigsByTableId(decisionTableId);
         Iterator decisionRowIterator = decisionRows1.iterator();

         while(decisionRowIterator.hasNext()) {
            DecisionRow decisionRow = (DecisionRow)decisionRowIterator.next();
            Iterator<DecisionColumnConfig> decisionColumnConfigsIterator = decisionColumnConfigs1.iterator();

            while(decisionColumnConfigsIterator.hasNext()) {
               DecisionColumnConfig decisionColumnConfigCurrent = decisionColumnConfigsIterator.next();
               DecisionCell decisionCell = this.decisionCellService.getCellByRowIdAndColId(decisionRow.getId(), decisionColumnConfigCurrent.getId());
               if (decisionCell != null) {
                  decisionCell.setId((Long)null);
                  decisionCell.setRowId((Long)rowMap.get(decisionRow.getId()));
                  decisionCell.setColId((Long)colMap.get(decisionColumnConfigCurrent.getId()));
                  this.decisionCellService.save(decisionCell);
               }
            }
         }

         List<RuleVariable> decisionTableVariables = this.ruleVariableService.getByScopeAndScopeId(4, decisionTableId);
         Iterator var54 = decisionTableVariables.iterator();

         while(var54.hasNext()) {
            RuleVariable decisionTableVariable = (RuleVariable)var54.next();
            decisionTableVariable.setId((Long)null);
            decisionTableVariable.setScopeId(decisionTable.getId());
            this.ruleVariableService.save(decisionTableVariable);
         }
      }

      List<DecisionTree> decisionTrees = this.decisionTreeService.getDecisionTreesByPackageId(id);
      Iterator var28 = decisionTrees.iterator();

      while(var28.hasNext()) {
         DecisionTree decisionTree = (DecisionTree)var28.next();
         Long decisionTreeId = decisionTree.getId();
         decisionTree.setId((Long)null);
         decisionTree.setRulePackageId(rulePackage.getId());
         this.decisionTreeService.save(decisionTree);
         decisionColumnConfigs = this.treeNodeService.getTreeNodesByTreeId(decisionTreeId);
         nodeMap = new HashMap();
         Iterator var35 = decisionColumnConfigs.iterator();

         while(var35.hasNext()) {
            TreeNode treeNode = (TreeNode)var35.next();
            Long nodeId = treeNode.getId();
            treeNode.setTreeId(decisionTree.getId());
            treeNode.setId((Long)null);
            this.treeNodeService.save(treeNode);
            nodeMap.put(nodeId, treeNode.getId());
         }

         List<TreeNode> treeNodes1 = this.treeNodeService.getTreeNodesByTreeId(decisionTree.getId());
         var37 = treeNodes1.iterator();

         while(var37.hasNext()) {
            TreeNode treeNode = (TreeNode)var37.next();
            if (treeNode.getParentId() != null) {
               treeNode.setParentId((Long)nodeMap.get(treeNode.getParentId()));
               this.treeNodeService.updateById(treeNode);
            }
         }

         treeDedutions = this.treeDedutionService.getTreeNodesByTreeId(decisionTreeId);
         var14 = treeDedutions.iterator();

         while(var14.hasNext()) {
            TreeDedution treeDedution = (TreeDedution)var14.next();
            treeDedution.setTreeId(decisionTree.getId());
            treeDedution.setNodeId((Long)nodeMap.get(treeDedution.getNodeId()));
            treeDedution.setId((Long)null);
            this.treeDedutionService.save(treeDedution);
         }

         List<RuleVariable> decisionTreeVariables = this.ruleVariableService.getByScopeAndScopeId(5, decisionTreeId);
         var43 = decisionTreeVariables.iterator();

         while(var43.hasNext()) {
            RuleVariable decisionTreeVariable = (RuleVariable)var43.next();
            decisionTreeVariable.setId((Long)null);
            decisionTreeVariable.setScopeId(decisionTree.getId());
            this.ruleVariableService.save(decisionTreeVariable);
         }
      }

   }

   public List<RulePackage> getRulePackages(String groupId, String artifactId) {
      if (!StringUtils.isBlank(groupId) && !StringUtils.isBlank(artifactId)) {
         LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.eq(RulePackage::getGroupId,groupId).eq(RulePackage::getArtifactId,artifactId).eq(RulePackage::getStatus,0);
         return this.baseMapper.selectList(queryWrapper);
      } else {
         return null;
      }
   }

   public List<RulePackage> findByName(String name) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getStatus,0);

      if (!StringUtils.isBlank(name)) {
         queryWrapper.like(RulePackage::getName, "%" + name + "%");

      }
      return this.baseMapper.selectList(queryWrapper);


   }

   public List<RulePackage> getRulePackagesByProjectId(long projectId) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getProjectid,projectId).eq(RulePackage::getStatus,0);
      return this.baseMapper.selectList(queryWrapper);
   }

   public List<PackagePermissions> getPermissionPacakge(long projectId) throws InvocationTargetException, IllegalAccessException {


      String userId = this.userHolder.getUser().getUserId();

      List<Long> groupIds = new ArrayList();
      List<SysGroupUserRole> sysGroupUserRoles = this.sysGroupUserRoleService.getByUserId(Long.valueOf(userId));
      Iterator iterator = sysGroupUserRoles.iterator();

      while(iterator.hasNext()) {
         SysGroupUserRole sysGroupUserRole = (SysGroupUserRole)iterator.next();
         groupIds.add(sysGroupUserRole.getGroupId());
      }

      LambdaQueryWrapper<PermissionReference> queryWrapperWithUserId = new LambdaQueryWrapper<>();
      LambdaQueryWrapper<PermissionReference> queryWrapperWithGroupIds = new LambdaQueryWrapper<>();
      //PermissionReferenceExample example = new PermissionReferenceExample();
      //PermissionReferenceExample example1 = new PermissionReferenceExample();

      queryWrapperWithUserId.eq(PermissionReference::getTargetId,projectId).eq(PermissionReference::getTargetType,0);
      queryWrapperWithUserId.eq(PermissionReference::getOwnerType,0).eq(PermissionReference::getOwnerId,Long.valueOf(userId));
      queryWrapperWithGroupIds.eq(PermissionReference::getTargetId,projectId).eq(PermissionReference::getTargetType,0);
      queryWrapperWithGroupIds.eq(PermissionReference::getOwnerType,1).in(PermissionReference::getOwnerId,groupIds);

      //example.createCriteria().andTargetIdEqualTo(projectId).andTargetTypeEqualTo(0).andOwnerIdEqualTo(Long.valueOf(userId)).andOwnerTypeEqualTo(0);
      //example1.createCriteria().andTargetIdEqualTo(projectId).andTargetTypeEqualTo(0).andOwnerIdIn(groupIds).andOwnerTypeEqualTo(1);
      ArrayList ownerIds;
      List<Long> groupIds1 = userGroupService.getGroupIds(userId);
      if (groupIds.size() == 0) {
         if (this.permissionService.count(queryWrapperWithUserId) == 0) {
            return this.getPackagePermissions(queryWrapperWithUserId, queryWrapperWithGroupIds, projectId, userId, groupIds);
         } else {
            ownerIds = Lists.newArrayList();
            ownerIds.add(userId);

            ownerIds.addAll(groupIds1);
            return this.permissionService.selectPackageOfPermission(projectId, ownerIds);
         }
      } else if (this.permissionService.list(queryWrapperWithUserId) == null && this.permissionService.list(queryWrapperWithGroupIds) == null) {
         return this.getPackagePermissions(queryWrapperWithUserId, queryWrapperWithGroupIds, projectId, userId, groupIds);
      } else {
         ownerIds = Lists.newArrayList();
         ownerIds.add(userId);
         ownerIds.addAll(groupIds1);
         return this.permissionService.selectPackageOfPermission(projectId, ownerIds);
      }
   }

   public List<PackagePermissions> getPackagePermissions(LambdaQueryWrapper<PermissionReference> queryWrapperWithUserId, LambdaQueryWrapper<PermissionReference> queryWrapperWithGroupIds, long projectId, String userId, List<Long> ids) {
      List<RulePackage> rulePackages = this.getRulePackagesByProjectId(projectId);
      List<RulePackage> packages = new ArrayList();
      queryWrapperWithUserId = new LambdaQueryWrapper<>();
      queryWrapperWithUserId.eq(PermissionReference::getOwnerId,Long.valueOf(userId)).eq(PermissionReference::getOwnerType,0).eq(PermissionReference::getTargetType,1);

      List permissionReferences;
      int i;
      int j;
      if (ids.size() > 0) {
         queryWrapperWithGroupIds = new LambdaQueryWrapper<>();
         queryWrapperWithGroupIds.eq(PermissionReference::getOwnerType,1).in(PermissionReference::getOwnerId,ids).eq(PermissionReference::getTargetType,1);
         //queryWrapperWithGroupIds.createCriteria().andOwnerIdIn(ids).andOwnerTypeEqualTo(1).andTargetTypeEqualTo(1);
         permissionReferences = this.permissionService.list(queryWrapperWithGroupIds);

         for(i = 0; i < rulePackages.size(); ++i) {
            for(j = 0; j < permissionReferences.size(); ++j) {
               if (((RulePackage)rulePackages.get(i)).getId().equals(((PermissionReference)permissionReferences.get(j)).getTargetId())) {
                  packages.add(rulePackages.get(i));
               }
            }
         }
      }

      permissionReferences = this.permissionService.list(queryWrapperWithUserId);

      for(i = 0; i < rulePackages.size(); ++i) {
         for(j = 0; j < permissionReferences.size(); ++j) {
            if (((RulePackage)rulePackages.get(i)).getId().equals(((PermissionReference)permissionReferences.get(j)).getTargetId())) {
               packages.add(rulePackages.get(i));
            }
         }
      }

      for(i = 0; i < packages.size() - 1; ++i) {
         for(j = packages.size() - 1; j > i; --j) {
            if (((RulePackage)packages.get(j)).getId().equals(((RulePackage)packages.get(i)).getId())) {
               packages.remove(j);
            }
         }
      }

      List<PackagePermissions> packagePermissionses = new ArrayList(packages.size());

      for(j = 0; j < packages.size(); ++j) {
         PackagePermissions packagePermissions = new PackagePermissions();
         packagePermissions.setId(((RulePackage)packages.get(j)).getId());
         packagePermissions.setName(((RulePackage)packages.get(j)).getName());
         packagePermissionses.add(packagePermissions);
      }

      return packagePermissionses;
   }

   public List<Map<String, Object>> getRulePackMenu(long rulePackageId) {
      List<Map<String, Object>> assemblyMenu = this.ruleAssemblyService.getRuleAssemblyMenu(rulePackageId);
      List<Map<String, Object>> tableMenu = this.decisionTableService.loadDecisionTable(rulePackageId);
      List<Map<String, Object>> treeMenu = this.decisionTreeService.loadDecisionTrees(rulePackageId);
      assemblyMenu.addAll(tableMenu);
      assemblyMenu.addAll(treeMenu);
      return assemblyMenu;
   }

   public List<RulePackage> getPackage() {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getStatus,1);
      return this.baseMapper.selectList(queryWrapper);

   }

   public IPage<RulePackage> getPagePackage(IPage<RulePackage> page, String name) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();


      RuleUser ruleUser = (RuleUser)this.userHolder.getUser();
      List list;
      if (name != null && name != "") {
         if (this.ruleUserRoleService.getByUserId(ruleUser.getId()).getRoleId() == Constant.PERMISSION_ADMIN) {
            queryWrapper.eq(RulePackage::getStatus, 1);
            queryWrapper.like(RulePackage::getName,"%" + name + "%");
            //example.createCriteria().andStatusEqualTo(1).andNameLike("%" + name + "%");
         } else {
            list = this.projectService.getProjectCode(ruleUser);
            queryWrapper.eq(RulePackage::getStatus, 1);
            queryWrapper.like(RulePackage::getName,"%" + name + "%");
            queryWrapper.in(RulePackage::getGroupId,list);
            //example.createCriteria().andStatusEqualTo(1).andGroupIdIn(list).andNameLike("%" + name + "%");
         }
      } else if (this.ruleUserRoleService.getByUserId(ruleUser.getId()).getRoleId() == Constant.PERMISSION_ADMIN) {
         queryWrapper.eq(RulePackage::getStatus, 1);
         //example.createCriteria().andStatusEqualTo(1);
      } else {
         list = this.projectService.getProjectCode(ruleUser);
         if (list.isEmpty()) {
            queryWrapper.eq(RulePackage::getStatus, 1);
            queryWrapper.eq(RulePackage::getGroupId,"-1");
            //example.createCriteria().andStatusEqualTo(1).andGroupIdEqualTo("-1");
         } else {
            queryWrapper.eq(RulePackage::getStatus, 1);
            queryWrapper.in(RulePackage::getGroupId,list);
            //example.createCriteria().andStatusEqualTo(1).andGroupIdIn(list);
         }
      }

      return this.baseMapper.selectPage(page, queryWrapper);
      //return this.selectPageByExample(example);
   }

   public List<RulePackage> getPackageByGroupId(String groupId) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getGroupId, groupId).eq(RulePackage::getStatus, 0);
      return this.list(queryWrapper);

   }

   public List<RulePackage> getAll(Long projectId) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(RulePackage::getProjectid, projectId).eq(RulePackage::getStatus, 0);
      return this.list(queryWrapper);
   }

   public void updateByProjectId(Long projectId, String groupId) {

      List<RulePackage> rulePackages = this.getAll(projectId);

      for(int i = 0; i < rulePackages.size(); ++i) {
         ((RulePackage)rulePackages.get(i)).setGroupId(groupId);
         this.updateById(rulePackages.get(i));
      }

   }

   public IPage<RulePackage> queryPagePackages(String groupId, String artifactId, IPage<RulePackage> page) {
      if (!StringUtils.isBlank(groupId) && !StringUtils.isBlank(artifactId)) {
         LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.eq(RulePackage::getGroupId, groupId).eq(RulePackage::getArtifactId, artifactId).ne(RulePackage::getStatus,0);
         return this.baseMapper.selectPage(page,queryWrapper);
      } else {
         return null;
      }
   }

   public void updateRuleAssemblyPriority(RuleMenuVO[] ruleMenuVOs) {
      RuleMenuVO[] var2 = ruleMenuVOs;
      int var3 = ruleMenuVOs.length;

      for(int var4 = 0; var4 < var3; ++var4) {
         RuleMenuVO ruleMenuVO = var2[var4];
         if (ruleMenuVO.getType() == 1) {
            DecisionTable decisionTable = new DecisionTable();
            decisionTable.setId(ruleMenuVO.getId());
            decisionTable.setPriority(ruleMenuVO.getPriority());
            this.decisionTableService.updateById(decisionTable);
         } else if (ruleMenuVO.getType() == 2) {
            DecisionTree decisionTree = new DecisionTree();
            decisionTree.setId(ruleMenuVO.getId());
            decisionTree.setPriority(ruleMenuVO.getPriority());
            this.decisionTreeService.updateById(decisionTree);
         } else {
            RuleAssembly ruleAssembly = new RuleAssembly();
            ruleAssembly.setId(ruleMenuVO.getId());
            ruleAssembly.setPriority(ruleMenuVO.getPriority());
            this.ruleAssemblyService.updateById(ruleAssembly);
         }
      }

   }

   public void updateRulePriority(RuleMenuVO[] ruleMenuVOs) {
      RuleMenuVO[] var2 = ruleMenuVOs;
      int var3 = ruleMenuVOs.length;

      for(int var4 = 0; var4 < var3; ++var4) {
         RuleMenuVO ruleMenuVO = var2[var4];
         Rule rule = new Rule();
         rule.setId(ruleMenuVO.getId());
         rule.setPriority(ruleMenuVO.getPriority().intValue());
         this.ruleService.updateById(rule);
      }

   }

   public void updateRuleAssemblyPriority(RuleMenuVO origRuleMenuVO, RuleMenuVO destMenuVO) {
      DecisionTable decisionTable;
      DecisionTree decisionTree;
      RuleAssembly ruleAssembly;
      if (origRuleMenuVO.getType() == 1) {
         decisionTable = new DecisionTable();
         decisionTable.setId(origRuleMenuVO.getId());
         decisionTable.setPriority(destMenuVO.getPriority());
         this.decisionTableService.updateById(decisionTable);
      } else if (origRuleMenuVO.getType() == 2) {
         decisionTree = new DecisionTree();
         decisionTree.setId(origRuleMenuVO.getId());
         decisionTree.setPriority(destMenuVO.getPriority());
         this.decisionTreeService.updateById(decisionTree);
      } else {
         ruleAssembly = new RuleAssembly();
         ruleAssembly.setId(origRuleMenuVO.getId());
         ruleAssembly.setPriority(destMenuVO.getPriority());
         this.ruleAssemblyService.updateById(ruleAssembly);
      }

      if (destMenuVO.getType() == 1) {
         decisionTable = new DecisionTable();
         decisionTable.setId(destMenuVO.getId());
         decisionTable.setPriority(origRuleMenuVO.getPriority());
         this.decisionTableService.updateById(decisionTable);
      } else if (destMenuVO.getType() == 2) {
         decisionTree = new DecisionTree();
         decisionTree.setId(destMenuVO.getId());
         decisionTree.setPriority(origRuleMenuVO.getPriority());
         this.decisionTreeService.updateById(decisionTree);
      } else {
         ruleAssembly = new RuleAssembly();
         ruleAssembly.setId(destMenuVO.getId());
         ruleAssembly.setPriority(origRuleMenuVO.getPriority());
         this.ruleAssemblyService.updateById(ruleAssembly);
      }

   }

   public void updateRulePriority(RuleMenuVO origRuleMenuVO, RuleMenuVO destMenuVO) {
      Rule origRule = new Rule();
      origRule.setId(origRuleMenuVO.getId());
      origRule.setPriority(destMenuVO.getPriority().intValue());
      Rule destRule = new Rule();
      destRule.setId(destMenuVO.getId());
      destRule.setPriority(origRuleMenuVO.getPriority().intValue());
      this.ruleService.updateById(origRule);
      this.ruleService.updateById(destRule);
   }

   public Byte getPriority(Long id) {
      byte maxPriority = this.baseMapper.getPriority(id);
      return (byte)(maxPriority + 1);
   }

   public void updateRulePackageInstallVO(RulePackage rulePackage) {
      RulePackage oldPackage = (RulePackage)this.getById(rulePackage.getId());
      if (!oldPackage.getArtifactId().equals(rulePackage.getArtifactId())) {
         this.unitCaseService.updateByArtifactId(oldPackage.getArtifactId(), rulePackage.getArtifactId(), rulePackage.getGroupId());
      }

      this.updateById(rulePackage);
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper();
      queryWrapper.eq(RulePackage::getBusinessModelId, rulePackage.getBusinessModelId()).ne(RulePackage::getVersion, rulePackage.getVersion());
      List<RulePackage> rulePackages = this.list(queryWrapper);
      if (rulePackages.size() > 0) {
         for(int i = 0; i < rulePackages.size(); ++i) {
            ((RulePackage)rulePackages.get(i)).setName(rulePackage.getName());
            ((RulePackage)rulePackages.get(i)).setArtifactId(rulePackage.getArtifactId());
            ((RulePackage)rulePackages.get(i)).setRemark(rulePackage.getRemark());
            this.updateById(rulePackages.get(i));
         }
      }

   }

   public List<ViewAssemblyVO> getViewAssemblyVOs(long packageId) {
      List<RuleAssembly> assemblies = this.ruleAssemblyService.getRuleAssemblyByPackageIdAndStatus(packageId);
      List<ViewAssemblyVO> result1 = Streams.of(assemblies).map(new Function<RuleAssembly, ViewAssemblyVO>() {
         public ViewAssemblyVO apply(RuleAssembly input) {
            ViewAssemblyVO viewAssemblyVO = new ViewAssemblyVO();

            try {
               BeanUtils.copyProperties(viewAssemblyVO, input);
            } catch (Exception var4) {
            }

            return viewAssemblyVO;
         }
      }).collectToList();
      List<DecisionTable> tables = this.decisionTableService.getDecisionTablesByPackageIdAndStatus(packageId);
      List<ViewAssemblyVO> result2 = Streams.of(tables).map(new Function<DecisionTable, ViewAssemblyVO>() {
         public ViewAssemblyVO apply(DecisionTable input) {
            ViewAssemblyVO viewAssemblyVO = new ViewAssemblyVO();

            try {
               BeanUtils.copyProperties(viewAssemblyVO, input);
            } catch (Exception var4) {
            }

            viewAssemblyVO.setType(1);
            return viewAssemblyVO;
         }
      }).collectToList();
      if (!result2.isEmpty()) {
         result1.addAll(result2);
      }

      List<DecisionTree> trees = this.decisionTreeService.getDecisionTreesByPackageIdAndStatus(packageId);
      List<ViewAssemblyVO> result3 = Streams.of(trees).map(new Function<DecisionTree, ViewAssemblyVO>() {
         public ViewAssemblyVO apply(DecisionTree input) {
            ViewAssemblyVO viewAssemblyVO = new ViewAssemblyVO();

            try {
               BeanUtils.copyProperties(viewAssemblyVO, input);
            } catch (Exception var4) {
            }

            viewAssemblyVO.setType(2);
            return viewAssemblyVO;
         }
      }).collectToList();
      if (!result3.isEmpty()) {
         result1.addAll(result3);
      }

      result1.sort(new Comparator<ViewAssemblyVO>() {
         public int compare(ViewAssemblyVO o1, ViewAssemblyVO o2) {
            return o1.getPriority() - o2.getPriority();
         }
      });
      return result1;
   }

   public RulePackage getRulePackageByArtifactId(String artifactId) {
      LambdaQueryWrapper<RulePackage> queryWrapper = new LambdaQueryWrapper();
      queryWrapper.eq(RulePackage::getArtifactId,artifactId).eq(RulePackage::getStatus,1);
      return (RulePackage)this.baseMapper.selectOne(queryWrapper);

   }

   public List getPackageNames(Long ownerId) {

      //PermissionReferenceExample permissionReferenceExample = new PermissionReferenceExample();
      //permissionReferenceExample.createCriteria().andOwnerIdEqualTo(ownerId).andTargetTypeEqualTo(1);
      List<PermissionReference> permissionReferences = this.permissionService.getPermissionReferencesByOwnerId(ownerId);
      //List<PermissionReference> permissionReferences = this.permissionReferenceMapper.selectByExample(permissionReferenceExample);
      List list = new ArrayList();
      Iterator var5 = permissionReferences.iterator();

      while(var5.hasNext()) {
         PermissionReference permissionReference = (PermissionReference)var5.next();
         Map map = new HashMap();
         String targetId = permissionReference.getTargetId().toString();
         RulePackage rulePackage = this.getById(permissionReference.getTargetId());
         map.put("packageId",targetId);
         map.put("packageName", rulePackage.getName());

         map.put("projectName", this.projectService.getById(rulePackage.getProjectid()).getProjectName());
         list.add(map);
      }

      return list;
   }
}
